package top.malaoshi.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import top.malaoshi.Constants;
import top.malaoshi.entity.UserModel;
import top.malaoshi.vo.JsonResult;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class UserFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpSession session=request.getSession();

        UserModel um=(UserModel)session.getAttribute(Constants.USER_INFO);
        if(um==null){//未登录
            //提示未登录 json/地址
            JsonResult res=new JsonResult();
            res.setCode(1);
            res.setMsg("请您先登录");
            ObjectMapper om=new ObjectMapper();
            String json=om.writeValueAsString(res);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(json);
            out.flush();
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

}